package charlie.shop.web;

import com.charlie.beans.ShipmentOrder;
import com.charlie.beans.SoHistory;
import com.charlie.beans.StatusDict;
import com.charlie.sessions.ShipmentOrderFacadeLocal;
import com.charlie.sessions.StatusDictFacadeLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Order tracking servlet
 * 
 * @author Vitaliy Mostipaka <imprtat@gmail.com>
 */
@WebServlet(name = "OrderTrackingServlet", urlPatterns = {"/track", "/track/*"})
public class OrderTrackingServlet extends HttpServlet {

    @EJB
    ShipmentOrderFacadeLocal shipmentOrder;
    @EJB
    StatusDictFacadeLocal statusDictionary;
    
    StatusDict defaultStatus;
    
    @Override
    public void init () {
        defaultStatus = statusDictionary.find(1);
    }
    
    private boolean processRequest(String trackingnumberStr, HttpServletRequest request) {       
        int trackingNumber;
        try {
            trackingNumber = Integer.parseInt(trackingnumberStr);
        } catch(NumberFormatException ex) {
            return false;
        }
        
        ShipmentOrder so = shipmentOrder.find(trackingNumber);
        if (so == null) {
            request.setAttribute("error_not_found", 1);
            return false;
        }
        request.setAttribute("order", so);
        SoHistory last_change = null;
        for (SoHistory history : so.getSoHistoryCollection()) {
            if (last_change == null || last_change.getSoHistoryId() < history.getSoHistoryId()) {
                last_change = history;
            }
        }
        request.setAttribute("status", last_change != null 
                ? last_change.getStatusDictId().getStatusName() 
                : defaultStatus.getStatusName());
        return true;
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getPathInfo() != null) {
            if (processRequest(request.getPathInfo().substring(1), request)) {
                request.getRequestDispatcher("/tracking/order.jsp").forward(request, response);
                return;
            }
        }
        request.getRequestDispatcher("/tracking/form.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (processRequest(request.getParameter("id"), request)) {
            request.getRequestDispatcher("/tracking/order.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("/tracking/form.jsp").forward(request, response);
        }
    }
}
